package com.example.firstdemo.ui.screens.pages.addProblem.addProblem

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowForwardIos
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBackIosNew
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil3.compose.rememberAsyncImagePainter
import com.example.firstdemo.LocalTinyMessageBoxState
import com.example.firstdemo.ui.screens.components.FullPageLoading
import com.example.firstdemo.ui.screens.components.SnackbarType
import com.example.firstdemo.ui.screens.components.TinyMessageBox
import com.example.firstdemo.ui.screens.components.TopAppBar
import com.example.firstdemo.ui.screens.pages.addProblem.addProblem.data.AddProblemUIState
import com.example.firstdemo.ui.screens.pages.addProblem.addProblem.data.LocalAddProblemDataProvider
import com.example.firstdemo.ui.theme.AppTheme
import com.example.firstdemo.ui.theme.Space
import com.example.firstdemo.ui.theme.eColors
import com.example.firstdemo.utils.imageUri2Path
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@Composable
fun AddProblemScreen(
    padding: PaddingValues = PaddingValues(0.dp),
    uiState: AddProblemUIState,
    onBack: () -> Unit = {},
    onSelectCarriage: () -> Unit = {},
    onSelectPosition: () -> Unit = {},
    onSelectProblem: () -> Unit = {},
    onAddDescription: () -> Unit = {},
    onSave: (imgPath: String) -> Unit = {},
) {
    val tinyMessageBoxSate = LocalTinyMessageBoxState.current
    val context = LocalContext.current
    val vehicleData = uiState.vehicleData
    val positionData = uiState.positionData
    val problemData = uiState.problemDictData
    val descriptionData = uiState.descriptionData
    var uploading by remember { mutableStateOf(false) }

    // 创建变量存储图片URI列表
    var imageUri by remember { mutableStateOf<Uri?>(null) }

    // 创建图片选择器（Android 13+推荐）
    val photoPickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.PickVisualMedia(),
        onResult = { uri ->
            imageUri = uri
        }
    )

    fun getDataValidCheck(): String? {
        if (vehicleData == null) {
            return "请选择车辆"
        }
        if (positionData == null) {
            return "请选择部件"
        }
        if (problemData == null) {
            return "请选择故障"
        }
        if (imageUri == null) {
            return "请选择故障图片"
        }
        return null
    }

    fun dataValidCheck(): Boolean {
        getDataValidCheck()?.let { message ->
            CoroutineScope(Dispatchers.Main).launch {
                tinyMessageBoxSate
                    .showSnackbar(
                        type = SnackbarType.ERROR,
                        message = message,
                        actionLabel = null,
                        withDismissAction = true,
                        duration = SnackbarDuration.Short
                    )
            }
            return false
        }
        return true
    }

    Surface(
        Modifier
            .padding(
                PaddingValues(
                    start = padding.calculateStartPadding(LayoutDirection.Ltr),
                    top = 0.dp,
                    end = padding.calculateEndPadding(LayoutDirection.Ltr),
                    bottom = padding.calculateBottomPadding()
                )
            )
            .fillMaxSize()
    ) {
        Column {
            TopAppBar(
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(
                            imageVector = Icons.Filled.ArrowBackIosNew,
                            contentDescription = "Localized description"
                        )
                    }
                },
                actions = {
                    IconButton(onClick = {}) {}
                },
            ) {
                Text(
                    "新增故障",
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }

            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .verticalScroll(rememberScrollState())
            ) {
                Card(
                    modifier = Modifier.padding(
                        Space.medium,
                        Space.medium,
                        Space.medium,
                        0.dp
                    )
                ) {
                    val vehicleValue =
                        if (vehicleData != null) "${vehicleData.passTime} ${vehicleData.stationName} ${vehicleData.carriage.carriageOrder} ${vehicleData.carriage.carriageNo}"
                        else "无"
                    ListItem(
                        label = { Text("车辆") },
                        value = {
                            Text(
                                text = vehicleValue,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                        },
                        modifier = Modifier.clickable(onClick = onSelectCarriage)
                    )
                    HorizontalDivider(thickness = 1.dp, color = MaterialTheme.eColors.border.base)

                    val positionValue =
                        if (positionData != null) "${positionData.label}[${positionData.value}]" else "无"
                    ListItem(
                        label = { Text("部件") },
                        value = {
                            Text(
                                text = positionValue,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                        },
                        modifier = Modifier.clickable(onClick = onSelectPosition)
                    )
                    HorizontalDivider(thickness = 1.dp, color = MaterialTheme.eColors.border.base)

                    val problemValue =
                        if (problemData != null) "${problemData.label}[${problemData.value}]" else "无"
                    ListItem(
                        label = { Text("故障") },
                        value = {
                            Text(
                                text = problemValue,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                        },
                        modifier = Modifier.clickable(onClick = onSelectProblem)
                    )
                    HorizontalDivider(thickness = 1.dp, color = MaterialTheme.eColors.border.base)

                    ListItem(
                        label = { Text("描述") },
                        value = {
                            Text(
                                text = if (descriptionData != "") descriptionData else "无",
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                        },
                        modifier = Modifier.clickable(onClick = onAddDescription)
                    )
                }
                Card(
                    modifier = Modifier.padding(
                        Space.medium,
                        Space.medium,
                        Space.medium,
                        0.dp
                    )
                ) {
                    Box(Modifier.padding(Space.medium)) {
                        Column {
                            Text(
                                text = "故障图片",
                                fontSize = 14.sp
                            )
                            Spacer(Modifier.height(Space.small))
                            Box(
                                contentAlignment = Alignment.Center,
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                if (imageUri != null) {
                                    Surface(
                                        shape = MaterialTheme.shapes.medium,
                                        border = BorderStroke(
                                            1.dp,
                                            MaterialTheme.eColors.border.base
                                        ),
                                        modifier = Modifier.fillMaxWidth()
                                    ) {
                                        Image(
                                            painter = rememberAsyncImagePainter(model = imageUri),
                                            contentDescription = null,
                                            contentScale = ContentScale.FillWidth,
                                            modifier = Modifier.fillMaxWidth()
                                        )
                                    }
                                } else {
                                    Surface(
                                        shape = MaterialTheme.shapes.medium,
                                        border = BorderStroke(
                                            1.dp,
                                            MaterialTheme.eColors.border.base
                                        ),
                                        modifier = Modifier.clickable(
                                            onClick = {
                                                photoPickerLauncher.launch(
                                                    PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
                                                )
                                            }
                                        )
                                    ) {
                                        Box(
                                            contentAlignment = Alignment.Center,
                                            modifier = Modifier
                                                .width(220.dp)
                                                .height(140.dp)
                                        ) {
                                            Icon(
                                                Icons.Filled.Add,
                                                contentDescription = null,
                                                modifier = Modifier.size(80.dp),
                                                tint = MaterialTheme.eColors.text.placeholder
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                Box(
                    modifier = Modifier.padding(
                        Space.medium,
                        Space.medium,
                        Space.medium,
                        0.dp
                    )
                ) {
                    Button(
                        shape = MaterialTheme.shapes.medium,
                        onClick = {
                            if (dataValidCheck()) {
                                uploading = true
                                onSave(context.imageUri2Path(imageUri!!)!!)
                            }
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(40.dp)
                    ) {
                        Text(
                            text = "保存",
                            color = MaterialTheme.eColors.basic.white
                        )
                    }
                }
            }
        }
        if (uploading) {
            FullPageLoading(
                text = "上传中"
            )
        }
        TinyMessageBox(tinyMessageBoxSate)
    }
}

@Composable
fun ListItem(
    label: @Composable () -> Unit,
    value: @Composable () -> Unit,
    modifier: Modifier = Modifier,
    showArrow: Boolean = true,
    contentPadding: PaddingValues = PaddingValues(Space.medium)
) {
    Row(
        horizontalArrangement = Arrangement.SpaceBetween,
        modifier = modifier
            .fillMaxWidth()
            .background(
                MaterialTheme.eColors.background.base
            )
            .padding(contentPadding)
    ) {
        label()
        CompositionLocalProvider(
            LocalContentColor provides MaterialTheme.eColors.text.placeholder,
            LocalTextStyle provides LocalTextStyle.current.copy(
                color = MaterialTheme.eColors.text.placeholder
            )
        ) {
            Row(Modifier.height(IntrinsicSize.Min)) {
                value()
                if (showArrow) {
                    Spacer(Modifier.width(Space.small))
                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier.fillMaxHeight()
                    ) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowForwardIos,
                            contentDescription = null,
                            modifier = Modifier.size(14.dp)
                        )
                    }
                }
            }
        }
    }
}

@Preview(
    showSystemUi = true
)
@Composable
fun AddProblemScreenPreview() {
    AppTheme {
        AddProblemScreen(
            padding = PaddingValues(top = 30.dp),
            uiState = LocalAddProblemDataProvider.uiState
        )
    }
}